package csu.web.dining.web.servlet;

import csu.web.dining.domain.Account;
import csu.web.dining.domain.Product;
import csu.web.dining.service.AccountService;
import csu.web.dining.service.CatalogService;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;
import java.util.List;

public class SignOnServlet extends HttpServlet {
    private String username;
    private String password;
    private String msg;

    private static final String SIGN_ON_FORM = "/WEB-INF/jsp/account/signon.jsp";

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.username = req.getParameter("username");
        this.password = req.getParameter("password");
        //检验用户名和密码的正确性
        if(!validate()){
            req.setAttribute("signOnMsg", this.msg);
            req.getRequestDispatcher(SIGN_ON_FORM).forward(req, resp);
        }
        else {
            AccountService accountService = new AccountService();
            Account loginAccount=accountService.getAccount(username, password);
            if(loginAccount==null){
                this.msg="用户名或密码错误";
                req.setAttribute("signOnMsg", this.msg);
                req.getRequestDispatcher(SIGN_ON_FORM).forward(req, resp);
            }
            else{
                HttpSession session = req.getSession();
                session.setAttribute("loginAccount", loginAccount);

                if(loginAccount.isListOption()){
                    CatalogService catalogService = new CatalogService();
                    List<Product> myList=catalogService.getProductListByCategory(loginAccount.getFavouriteCategoryId());
                    session.setAttribute("myList", myList);
                }

                resp.sendRedirect("mainForm");//在post方法中请求也是post方法，所以对面也要用post方法接收
            }
        }
    }

    //校验用户名和密码的正确性
    private boolean validate(){
        if(this.username==null|| this.username.equals("")){
            this.msg="用户名不能为空";
            return false;
        }
        if(this.password==null|| this.password.equals("")){
            this.msg="密码不能为空";
            return false;
        }
        return true;
    }
}

